import React, { useState, useEffect, useRef, useCallback } from 'react';
import { CFormSelect, CFormLabel, CCol, CRow, CFormInput, CButton } from '@coreui/react';
import { useSelector } from 'react-redux'

const Forecast = () => {
    const [statistics, setStatistics] = useState([]);
    const [statisticFile, setStatisticFile] = useState('');
    const [loading, setLoading] = useState(false);
    const [progress, setProgress] = useState(0); 
    const progressBarRef = useRef(null);
    const [messages, setMessages] = useState([]);
    const [forecastName, setForecastName] = useState('');
    const token = useSelector((state) => state.token);

    const fetchStatistics = useCallback(async () => {
        setLoading(true);
        try {
            const response = await fetch(`${process.env.REACT_APP_SERVER_ADDRESS}/api/v1/statistics/filename`,
                {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                }
            );
            const data = await response.json();
            setStatistics(data);
            if (data.length > 0) {
                setStatisticFile(data[0].filename);
            }
        } catch (error) {
            console.error('Failed to fetch statistics:', error);
        } finally {
            setLoading(false);
        }
    }, []);

    useEffect(() => {
        fetchStatistics();
    }, []);

    const handleFileChange = (event) => {
        setStatisticFile(event.target.value);
    };

    const handleForecastNameChange = (event) => {
        setForecastName(event.target.value);
    };

    const handlePrepareForecast = async () => {
        if (!forecastName) {
            alert('Файл прогноза не выбран');
            return;
        }
    
        try {
            const response = await fetch(`${process.env.REACT_APP_SERVER_ADDRESS}/api/v1/tasks/tasks_forecast`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({
                    statistics_filename: statisticFile,
                    forecast_name: forecastName,
                }),
            });
    
            if (!response.ok) {
                throw new Error(`HTTP error status: ${response.status}`);
            } else {
                console.log("Запрос успешно выполнен");
            }
        } catch (error) {
            console.error("Ошибка при выполнении запроса:", error);
        }
    };


    const updateProgress = (value) => {
        setProgress(value);
        if (progressBarRef.current) {
            progressBarRef.current.style.width = `${value}%`;
        }
    };

    useEffect(() => {
        const intervalId = setInterval(async () => {
            try {
                const response = await fetch(`${process.env.REACT_APP_SERVER_ADDRESS}/api/v1/tasks/tasks?task_type=forecast`,
                    {
                        method: 'GET',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': `Bearer ${token}`
                        },
                    }
                );
                if (response.ok) {
                    const data = await response.json();
                    setMessages(data);
                    if (data.progress!== undefined) {
                        setProgress(data.progress);
                    }
                }
            } catch (error) {
                console.error("Ошибка при выполнении запроса:", error);
            }
        }, 1000);

        return () => clearInterval(intervalId);
    }, []);

    return (
        <>
            <h1>Сформировать прогноз</h1>
            <br></br>
            <CRow>
                <CCol xs={2}>
                    <CFormLabel>Файл статистики</CFormLabel>
                </CCol>
                <CCol xs={3}>
                    <CFormSelect 
                        aria-label="Выберите файл статистики"
                        options={statistics.map(item => ({
                        label: item.filename,
                        value: item.filename,
                        }))}
                        onChange={handleFileChange}
                    />
                </CCol>
            </CRow>
            <br></br>
            <CRow>
                <CCol xs={2}>
                    <CFormLabel>Название прогноза</CFormLabel>
                </CCol>
                <CCol xs={3}>
                    <CFormInput
                        type="text"
                        placeholder="название прогноза"
                        aria-label="sm input example"
                        onChange={handleForecastNameChange}
                    />
                </CCol>
            </CRow>
            <br></br>
            <CRow>
                <CCol xs={2}>
                    <CButton color="light" variant="outline" onClick={handlePrepareForecast}>Сформировать</CButton>
                </CCol>
            </CRow>
            <br></br>
            <CRow>
                <CCol xs={2}>
                    <CFormLabel>Прогресс</CFormLabel>
                </CCol>
                <CCol xs={3}>
                    <div ref={progressBarRef} style={{ width: '100%', backgroundColor: 'lightgray' }}>
                        <div style={{ width: `${progress}%`, height: '20px', backgroundColor: 'grey' }}></div>
                    </div>
                </CCol>
            </CRow>
            <br></br>
            <CRow>
                <CCol xs={2}>
                    <CFormLabel>Результат последней задачи</CFormLabel>
                </CCol>
                <CCol xs={3}>
                    {messages?.msg?.map((message, index) => (
                        <div key={index}>{message}</div>
                    ))}
                    {messages?.error && <div style={{color: 'red'}}>{messages.error}</div>}
                </CCol>

            </CRow>
        </>
    );
};

export default Forecast;
